//
//  PK-ios
//
//  Created by Seven on 15/9/15.
//  Copyright (c) 2015年 Seven. All rights reserved.
//

#import "NSString+Category.h"

@implementation NSString (Category)


+ (NSString *)getLastFontString:(NSString *)urlString {
    int index = 0;
  const char *chars = [urlString cStringUsingEncoding:NSUTF8StringEncoding];
    for (int i = 0; i < strlen(chars); i++) {
        if (chars[i] == '/') {
            index = i;
        }
    }
    return  [urlString substringFromIndex:index+1];
}

+ (NSString*) getSecrectStringWithPhoneNumber:(NSString*)phoneNum
{
    if (phoneNum.length==11) {
        NSMutableString *newStr = [NSMutableString stringWithString:phoneNum];
        NSRange range = NSMakeRange(3, 7);
        [newStr replaceCharactersInRange:range withString:@"*****"];
        return newStr;
    }
    return nil;
}

- (NSString*)secrectStringWithPhoneNumber {
    NSString *s1 = [self substringToIndex:3];
    NSString *s2 = [self substringFromIndex:7];
    return [NSString stringWithFormat:@"%@****%@",s1,s2];
}

+ (NSString*) getSecrectStringWithAccountNo:(NSString*)accountNo
{
    NSMutableString *newStr = [NSMutableString stringWithString:accountNo];
    NSRange range = NSMakeRange(4, 8);
    if (newStr.length>12) {
        [newStr replaceCharactersInRange:range withString:@" **** **** "];
    }
    return newStr;
}

+ (NSString*) stringMobileFormat:(NSString *)mobile {
    if (mobile.length==11) {
        NSMutableString* value = [[NSMutableString alloc] initWithString:mobile];
        [value insertString:@"-" atIndex:3];
        [value insertString:@"-" atIndex:8];
        return value;
    }
    
    return nil;
}

+ (NSString*) stringChineseFormat:(double)value{
    
    if (value / 100000000 >= 1) {
        return [NSString stringWithFormat:@"%.0f亿",value/100000000];
    }
    else if (value / 10000 >= 1 && value / 100000000 < 1) {
        return [NSString stringWithFormat:@"%.0f万",value/10000];
    }
    else {
        return [NSString stringWithFormat:@"%.0f",value];
    }
}

+ (NSString*)stringWMFormat:(long)number{
    NSString *numStr = @"";
    if (number < 10000000) {
        numStr = [self countNumAndChangeformat:number];
    }else {//百万
        numStr = [NSString stringWithFormat:@"%.1fm",number/1000000.0];
    }
    return numStr;
}


+ (NSString*) stringKWFormat:(long)value{
    if (value < 10000) {
        return [NSString stringWithFormat:@"%ld",(long)value];
    }else if (value < 1000000) {
        return [NSString stringWithFormat:@"%0.1fk",value/1000.0];
    }else {
        return [NSString stringWithFormat:@"%0.1fm",value/10000000.0];
    }
}

+(NSString *)countNumAndChangeformat:(long)number
{
    NSNumberFormatter *mtFormatter = [[NSNumberFormatter alloc] init];
    mtFormatter.positiveFormat = @"###,###";
    return [mtFormatter stringFromNumber:@(number)];
}


//保留两位c小数 不四舍五入
+ (NSString *)stringWithDecimalTwo:(CGFloat)decimal{
    int new = decimal*100;
    return [NSString stringWithFormat:@"%0.2f", new/100.0];
}


-(CGFloat)heightWithFontSize:(CGFloat)fontSize width:(CGFloat)width
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    return  [self boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.height;
}
-(CGFloat)heightWithFont:(UIFont *)font width:(CGFloat)width
{
    NSDictionary *attrs = @{NSFontAttributeName:font};
    return  [self boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.height;
}
- (CGFloat)widthWithFontSize:(CGFloat)fontSize height:(CGFloat)maxHeight
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    return  [self boundingRectWithSize:CGSizeMake(0, maxHeight) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.width;
}

- (NSNumber*)toNumber
{
    NSNumberFormatter *formatter=[[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *number=[formatter numberFromString:self];
    return number;
}

/*抹除运费小数末尾的0*/
- (NSString *)removeUnwantedZero {
    if ([[self substringWithRange:NSMakeRange(self.length- 3, 3)] isEqualToString:@"000"]) {
        return [self substringWithRange:NSMakeRange(0, self.length-4)]; // 多一个小数点
    } else if ([[self substringWithRange:NSMakeRange(self.length- 2, 2)] isEqualToString:@"00"]) {
        return [self substringWithRange:NSMakeRange(0, self.length-2)];
    } else if ([[self substringWithRange:NSMakeRange(self.length- 1, 1)] isEqualToString:@"0"]) {
        return [self substringWithRange:NSMakeRange(0, self.length-1)];
    } else {
        return self;
    }
}

//去掉前后空格
- (NSString *)trimmedString{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)removeMiniSpace{
    NSMutableString *string = [NSMutableString string];
    NSRange range;
    for(int i=0; i<self.length; i+=range.length){
        range = [self rangeOfComposedCharacterSequenceAtIndex:i];
        NSString *s = [self substringWithRange:range];
        int c = [self characterAtIndex:i];
        if (c != 65279) {//@""h长度为1的空白占位符
            [string appendString:s];
        }
    }
    return string;
}


//版本号转换
- (NSInteger)toVersionCode {
    //TODO 正则判断 异常处理
    NSArray *array = [self componentsSeparatedByString:@"."];
    NSInteger infoCode = 0;
    NSInteger multiply = 1;
    for (NSInteger i = array.count; i > 0; i--) {
        NSString *numberString = array[i - 1];
        NSInteger intNumber = [numberString integerValue] * multiply;
        infoCode += intNumber;
        multiply *= 1000;
    }
    return infoCode;
}


- (NSUInteger)textLength {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < self.length; i++) {
        unichar uc = [self characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger unicodeLength = asciiLength;
    return unicodeLength;
}

- (NSString *)deleteSpace {
  return  [self stringByReplacingOccurrencesOfString:@" "withString:@""];
}

- (NSString *)unicodeToChinese{
    if (self.length == 0) {
        return self;
    }
    NSMutableString *convertedString = [self mutableCopy];
    [convertedString replaceOccurrencesOfString:@"\\U" withString:@"\\u" options:0 range:NSMakeRange(0, convertedString.length)];
    CFStringRef transform = CFSTR("Any-Hex/Java");
    CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);
    return convertedString;
}



//+ (NSString *)countNumAndChangeformat:(NSInteger)currentGdCount   {
//    NSString *num = @(currentGdCount).stringValue;
//    int count = 0;
//    long long int a = num.longLongValue;
//    while (a != 0)
//    {
//        count++;
//        a /= 10;
//    }
//    NSMutableString *string = [NSMutableString stringWithString:num];
//    NSMutableString *newstring = [NSMutableString string];
//    while (count > 3) {
//        count -= 3;
//        NSRange rang = NSMakeRange(string.length - 3, 3);
//        NSString *str = [string substringWithRange:rang];
//        [newstring insertString:str atIndex:0];
//        [newstring insertString:@"," atIndex:0];
//        [string deleteCharactersInRange:rang];
//    }
//    [newstring insertString:string atIndex:0];
//    return newstring;
//}

- (NSMutableArray *)charArr{
    NSMutableArray *arr = [NSMutableArray array];
    NSRange range;
    for(int i=0; i<self.length; i+=range.length){
        range = [self rangeOfComposedCharacterSequenceAtIndex:i];
        NSString *s = [self substringWithRange:range];
        [arr addObject:s];
    }
    return arr;
}

- (NSString *)numCoverToKeyString{
    NSMutableString *string = [NSMutableString string];
    NSRange range;
    for(int i=0; i<self.length; i+=range.length){
        range = [self rangeOfComposedCharacterSequenceAtIndex:i];
        NSString *s = [self substringWithRange:range];
        switch (s.intValue) {
            case 2:
                s = @"a";
                break;
            case 3:
                s = @"d";
                break;
            case 4:
                s = @"g";
                break;
            case 5:
                s = @"j";
                break;
            case 6:
                s = @"m";
                break;
            case 7:
                s = @"p";
                break;
            case 8:
                s = @"t";
                break;
            case 9:
                s = @"w";
                break;
                
            default:
                break;
        }
        [string appendString:s];
    }
    return string;
}


- (NSString *)reversed{
    NSUInteger i = 0;
    NSUInteger j = self.length - 1;
    unichar characters[self.length];
    while (i < j) {
        characters[j] = [self characterAtIndex:i];
        characters[i] = [self characterAtIndex:j];
        i ++;
        j --;
    }
    if(i == j)
        characters[i] = [self characterAtIndex:i];
    return [NSString stringWithCharacters:characters length:self.length];
}

static dispatch_queue_t workDelayQueue;
dispatch_queue_t delayQueue(void){
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        workDelayQueue = dispatch_queue_create("com.gk.keyboard.queue",DISPATCH_QUEUE_SERIAL);
    });
    return workDelayQueue;
}

-(void)enumerateSubStringWithPerLength:(NSInteger)len duration:(float)perSecond beginLocation:(NSInteger)location completeBlock:(void(^)(NSRange subRange, NSString *subString, NSError *err))block{
    
    if (nil == self || ![self isKindOfClass:[NSString class]]) {
        if (block) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSError *error = [NSError errorWithDomain:@"数据类型错误" code:-1 userInfo:nil];
                block(NSMakeRange(0, 0), nil, error);
            });
        }
    }else{
        __block NSInteger curLocation = location;
        NSInteger totalLen = self.length;
        __weak NSString *weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(perSecond * NSEC_PER_SEC)), delayQueue(), ^{
            @autoreleasepool {
                NSRange makeRange = NSMakeRange(curLocation, len);
                if (curLocation >= totalLen) {
                    NSLog(@"递归结束啦,释放资源");
                    return ;
                }
                if (makeRange.location + makeRange.length > totalLen) {
                    makeRange = NSMakeRange(makeRange.location, totalLen - makeRange.location);
                }
                makeRange = [weakSelf rangeOfComposedCharacterSequencesForRange:makeRange];
                NSString *subString = [weakSelf substringWithRange:makeRange];
                if (block) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        block(makeRange, subString, nil);
                    });
                }
                NSLog(@"range is %@  substring is %@",NSStringFromRange(makeRange),subString);
                curLocation += makeRange.length;
                [weakSelf enumerateSubStringWithPerLength:len duration:perSecond beginLocation:curLocation completeBlock:block];
            }
        });
    }
}


/**
 char * -> NSString
 */
+ (NSString *)stringWithChars:(char *)chars{
    //return @"1";
    CFIndex length = strlen(chars);
    CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
    CFMutableStringRef s = CFStringCreateMutable(kCFAllocatorDefault, maxSize);
    CFStringAppendCString(s, chars, kCFStringEncodingUTF8);
    NSString *str = (__bridge NSString *)s;
    CFRelease(s); 
    return str;
}


/**
 NSString  ->  char *
 */
- (char *)getChars{
    CFStringRef aString = (__bridge CFStringRef)self;
    if (aString == NULL) {
        return NULL;
    }
    CFIndex length = CFStringGetLength(aString);
    CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
    char *buffer = (char *)malloc(maxSize);
    if (CFStringGetCString(aString, buffer, maxSize, kCFStringEncodingUTF8)) {
       
    }
    CFRelease(aString);
    return buffer;
}

- (BOOL)isYoutubeVideoUrl{
    if ([self rangeOfString:@"www.youtube.com/watch"].location!=NSNotFound || [self rangeOfString:@"youtu.be/"].location!=NSNotFound) {
        return YES;
    }
    return NO;
}

- (NSString *)screenUrl{
    NSString *url = self;
    if ([url rangeOfString:@"?"].location == NSNotFound) {
        url = [url stringByAppendingFormat:@"?screen=1"];
    }else {
        url = [url stringByAppendingFormat:@"&screen=1"];
    }
    return url;
}

@end


@implementation NSNumber(string)
/** 数字转字符串*/
- (NSString *)coverToString{
    return [NSString stringWithFormat:@"%@", self];
}


- (NSString *)convertTimeString {
    int seconds = self.intValue;
    
    int minute = (seconds / 60);
    int second = (seconds % 60);
    return [NSString stringWithFormat:@"%d:%02d", minute, second];
}


- (NSString *)convertTimeString2 {
    long seconds = self.longValue;
    int hour = (seconds / 3600);
    
    seconds -= hour*3600;
    
    int minute = (seconds / 60);
    
    int second = seconds - minute*60;
    
    return [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second];
}


- (NSString *)numberString{
    long num = self.longValue;
    if (num < 1000) {
        return @(num).stringValue;
    }else if (num < 1000000) {
        CGFloat v = ((int)(num/100.0))/10.0;
        return [NSString stringWithFormat:@"%gk",v];
    }else {
        CGFloat v = ((int)(num/100000.0))/10.0;
        return [NSString stringWithFormat:@"%gm",v];
    }
}

@end







